package com.sskj.gocoin.v.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.jakewharton.rxbinding2.widget.RxAdapterView;
import com.sskj.gocoin.MyAppLication;
import com.sskj.gocoin.R;
import com.sskj.gocoin.common.App;
import com.sskj.gocoin.common.MoneyValueFilter;
import com.sskj.gocoin.common.adapter.BaseAdapter;
import com.sskj.gocoin.common.adapter.ViewHolder;
import com.sskj.gocoin.m.bean.HttpData;
import com.sskj.gocoin.m.bean.PayWayBean;
import com.sskj.gocoin.m.bean.TabEntity;
import com.sskj.gocoin.p.activity.FabiPublishPresenter;
import com.sskj.gocoin.utils.ClickUtil;
import com.sskj.gocoin.utils.TipUtil;
import com.sskj.gocoin.utils.ToastUtil;
import com.sskj.gocoin.v.base.BaseActivity;
import com.sskj.gocoin.v.widget.mychart.ArrowAdapter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;

import butterknife.BindView;

public class FabiPublishActivity extends BaseActivity<FabiPublishPresenter> {
    @BindView(R.id.spinner)
    Spinner spinner;
    @BindView(R.id.tv_add_pay_way)
    TextView tvAddPayWay;
    @BindView(R.id.commonTabLayout)
    CommonTabLayout commonTabLayout;
    @BindView(R.id.ll_back)
    LinearLayout ll_back;
    @BindView(R.id.iv_right)
    ImageView ivRight;  // 右侧图标---点击进入求购/出售列表
    @BindView(R.id.pay_way_recyclerview)
    RecyclerView mPayWayRecyclerview;
    @BindView(R.id.fabi_publish_count)
    EditText mFabiPublishCount;
    @BindView(R.id.fabi_publish_input_low)
    EditText mFabiPublishInputLow;
    @BindView(R.id.fabi_publish_input_hight)
    EditText mFabiPublishInputHight;
    @BindView(R.id.fabi_publish_input_unit_price)
    EditText mFabiPublishInputUnitPrice;  // 单价
    @BindView(R.id.fabi_publish_input_remark)
    EditText mFabiPublishInputRemark;
    //    @BindView(R.id.remark_layout)
//    LinearLayout mRemarkLayout;
    @BindView(R.id.bt_control)
    Button mBtControl;  // 出售按钮
    private String[] mTitles = {App.INSTANCE.getString(R.string.strFabiPublishActivity200), "发布购买"};
    private BaseAdapter<PayWayBean> mBaseAdapter;
    /**
     * 发布类型 0：出售，  or 求购
     */
    private int mIndex = 0;
    private int mPayWx;
    private int mPayAli;
    private int mPayBank;
    private int mPaypal;
    private View mFooterView;
    private View mFailView;
    private View mStartLading;
    private View mLoadingProgress;


    @Override
    protected int getLayoutResId() {
        return R.layout.activity_fabi_publish;
    }

    @Override
    public FabiPublishPresenter getPresenter() {
        return new FabiPublishPresenter();
    }

    @SuppressLint("CheckResult")
    @Override
    protected void initView() {
        mPresenter.requestUnitPrice();
        mPresenter.requsetPayWayList();
        ClickUtil.click(ll_back, this::finish);
        ClickUtil.click(ivRight, () -> {
            FabiDetailActivity.start(this);
//            FabiSellListActivity.start(this, mIndex == 1);
        });
        ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntity(mTitles[i]));
        }

        commonTabLayout.setTabData(mTabEntities);
        commonTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                mIndex = position;
                mBtControl.setText(position == 0 ? "发布出售" : "发布购买");
                mFabiPublishCount.setHint(position == 0 ? App.INSTANCE.getString(R.string.strFabiPublishActivity204) : App.INSTANCE.getString(R.string.strFabiPublishActivity205));
                mFabiPublishInputUnitPrice.setHint(position == 0 ? App.INSTANCE.getString(R.string.strFabiPublishActivity206) : App.INSTANCE.getString(R.string.strFabiPublishActivity207));
//                mRemarkLayout.setVisibility(position == 0 ? View.VISIBLE : View.GONE);
            }

            @Override
            public void onTabReselect(int position) {

            }
        });

        ArrowAdapter spinnerTypeAdapter = new ArrowAdapter(this,
                R.layout.item_publish_type, Arrays.asList(mTitles));
        spinnerTypeAdapter.setDropDownViewResource(R.layout.item_publish_type_drop);
        spinner.setAdapter(spinnerTypeAdapter);
        spinner.setSelection(0);
        RxAdapterView.itemSelections(spinner)
                .subscribe(pos -> {
                    mIndex = pos;
                    mBtControl.setText(mIndex == 0 ? "发布出售" : "发布购买");
                    mBtControl.setBackground(ContextCompat.getDrawable(this, mIndex == 0 ? R.drawable.green_bg : R.drawable.red_bg));
                    mFabiPublishCount.setHint(mIndex == 0 ? App.INSTANCE.getString(R.string.strFabiPublishActivity204) : App.INSTANCE.getString(R.string.strFabiPublishActivity205));
                    mFabiPublishInputUnitPrice.setHint(mIndex == 0 ? App.INSTANCE.getString(R.string.strFabiPublishActivity206) : App.INSTANCE.getString(R.string.strFabiPublishActivity207));
                });

        mFabiPublishInputHight.setFilters(new InputFilter[]{new MoneyValueFilter().setDigits(2)});
        mFabiPublishInputLow.setFilters(new InputFilter[]{new MoneyValueFilter().setDigits(2)});
        mFabiPublishInputUnitPrice.setFilters(new InputFilter[]{new MoneyValueFilter().setDigits(2)});
        mFabiPublishCount.setFilters(new InputFilter[]{new MoneyValueFilter().setDigits(4)});

        mPayWayRecyclerview.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
        mPayWayRecyclerview.setLayoutManager(new LinearLayoutManager(this) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        mBaseAdapter = new BaseAdapter<PayWayBean>(R.layout.recy_item_pay_way, null, mPayWayRecyclerview) {

            @Override
            public void bind(ViewHolder holder, PayWayBean item) {
                holder.setText(R.id.item_checkbox, item.getTip());
                if ("wx".equals(item.getType())) {
                    holder.setText(R.id.tv_pay_name, "微信");
                    holder.setImageResource(R.id.tv_pay_icon, R.mipmap.icon_wx);
                    ((CheckBox) holder.getView(R.id.item_checkbox)).setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.selector_checkbox, 0);
//                    ((CheckBox) holder.getView(R.id.item_checkbox)).setCompoundDrawablesWithIntrinsicBounds(R.mipmap.icon_wx, 0, R.drawable.selector_checkbox, 0);
                } else if ("alipay".equals(item.getType())) {
                    holder.setImageResource(R.id.tv_pay_icon, R.mipmap.icon_ali);
                    ((CheckBox) holder.getView(R.id.item_checkbox)).setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.selector_checkbox, 0);
//                    ((CheckBox) holder.getView(R.id.item_checkbox)).setCompoundDrawablesWithIntrinsicBounds(R.mipmap.icon_ali, 0, R.drawable.selector_checkbox, 0);
                } else if ("backcard".equals(item.getType())) {
                    holder.setText(R.id.tv_pay_name, "银联");
                    holder.setImageResource(R.id.tv_pay_icon, R.mipmap.icon_bank);
                    ((CheckBox) holder.getView(R.id.item_checkbox)).setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.selector_checkbox, 0);
//                    ((CheckBox) holder.getView(R.id.item_checkbox)).setCompoundDrawablesWithIntrinsicBounds(R.mipmap.icon_bank, 0, R.drawable.selector_checkbox, 0);
                } else if ("paypal".equals(item.getType())) {
                    holder.setText(R.id.tv_pay_name, "支付宝");
                    holder.setImageResource(R.id.tv_pay_icon, R.mipmap.pay_pal);
                    ((CheckBox) holder.getView(R.id.item_checkbox)).setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.selector_checkbox, 0);
//                    ((CheckBox) holder.getView(R.id.item_checkbox)).setCompoundDrawablesWithIntrinsicBounds(R.mipmap.pay_pal, 0, R.drawable.selector_checkbox, 0);
                }
                holder.setOnCheckedChangeListener(R.id.item_checkbox, new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        if (isChecked) {
                            if ("wx".equals(item.getType())) {
                                mPayWx = 1;
                            } else if ("alipay".equals(item.getType())) {
                                mPayAli = 1;
                            } else if ("backcard".equals(item.getType())) {
                                mPayBank = 1;
                            } else if ("paypal".equals(item.getType())) {
                                mPaypal = 1;
                            }
                        } else {
                            if ("wx".equals(item.getType())) {
                                mPayWx = 0;
                            } else if ("alipay".equals(item.getType())) {
                                mPayAli = 0;
                            } else if ("backcard".equals(item.getType())) {
                                mPayBank = 0;
                            } else if ("paypal".equals(item.getType())) {
                                mPaypal = 0;
                            }
                        }
                    }
                });
            }
        };
        ClickUtil.click(tvAddPayWay, () -> startActivity(new Intent(mActivity, SecurityCenterActivity.class)));

//        mFooterView = LayoutInflater.from(this).inflate(R.layout.item_text, null);
//        mFooterView.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                startActivity(new Intent(mActivity, SecurityCenterActivity.class));
//            }
//        });
        mFailView = LayoutInflater.from(this).inflate(R.layout.layout_reset_loading, null);
        mStartLading = mFailView.findViewById(R.id.start_loading);
        mLoadingProgress = mFailView.findViewById(R.id.loading_progress);
        mStartLading.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mStartLading.setVisibility(View.INVISIBLE);
                mLoadingProgress.setVisibility(View.VISIBLE);
                mPresenter.requsetPayWayList();
            }
        });


        mBtControl.setOnClickListener(v -> {
            String sumCount = mFabiPublishCount.getText().toString().trim();
            String lowPrice = mFabiPublishInputLow.getText().toString().trim();
            String hightPrice = mFabiPublishInputHight.getText().toString().trim();
            String unitPrice = mFabiPublishInputUnitPrice.getText().toString().trim();

            if (TextUtils.isEmpty(sumCount)) {
                ToastUtil.getInstance(MyAppLication.getApplication()).showMessage(App.INSTANCE.getString(R.string.strFabiPublishActivity217));
                return;
            } else if (TextUtils.isEmpty(lowPrice)) {
                ToastUtil.getInstance(MyAppLication.getApplication()).showMessage(App.INSTANCE.getString(R.string.strFabiPublishActivity218));
                return;
            } else if (TextUtils.isEmpty(hightPrice)) {
                ToastUtil.getInstance(MyAppLication.getApplication()).showMessage(App.INSTANCE.getString(R.string.strFabiPublishActivity219));
                return;
            } else if (TextUtils.isEmpty(unitPrice)) {
//                mPresenter.requestUnitPrice();
                ToastUtil.getInstance(MyAppLication.getApplication()).showMessage(App.INSTANCE.getString(R.string.strFabiPublishActivity220));
                return;
            } else if (mPayWx + mPayAli + mPayBank + mPaypal == 0) {
                ToastUtil.getInstance(MyAppLication.getApplication()).showMessage(App.INSTANCE.getString(R.string.strFabiPublishActivity221));
                return;
            }

            Double lowPriceD = Double.valueOf(lowPrice);
            Double hightPriceD = Double.valueOf(hightPrice);
            Double sumCountD = Double.valueOf(sumCount);
            Double unitPriceD = Double.valueOf(unitPrice);

            if (lowPriceD > hightPriceD) {
                ToastUtil.getInstance(MyAppLication.getApplication()).showMessage(App.INSTANCE.getString(R.string.strFabiPublishActivity222));
                return;
            } else if (lowPriceD < unitPriceD) {
                ToastUtil.getInstance(MyAppLication.getApplication()).showMessage(App.INSTANCE.getString(R.string.strFabiPublishActivity223));
                return;
            } else if (lowPriceD > unitPriceD * sumCountD) {
                ToastUtil.getInstance(MyAppLication.getApplication()).showMessage(App.INSTANCE.getString(R.string.strFabiPublishActivity224));
                return;
            }
//            String remark = mFabiPublishInputRemark.getText().toString().trim();
//            if (mIndex == 0 && TextUtils.isEmpty(remark)){
//                ToastUtil.getInstance(MyAppLication.getApplication()).showMessage(App.INSTANCE.getString(R.string.strFabiPublishActivity225));
//                return;
//            }
            TipUtil.publishConfirmTip(this, mIndex == 0 ? false : true, unitPrice, sumCount, String.valueOf(unitPriceD * sumCountD), new TipUtil.OnTipSure() {
                @Override
                public void onSure() {
                    mPresenter.requsetPublish(mIndex == 0 ? "sell" : "pmma", sumCount, lowPrice, hightPrice, unitPrice, mPayWx, mPayAli, mPayBank, mPaypal, "");
                }
            }).show();
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        mPresenter.requsetPayWayList();
    }

    public static void start(Context context) {
        Intent starter = new Intent(context, FabiPublishActivity.class);
        context.startActivity(starter);
    }

    public void onHttpFail() {
//        mBaseAdapter.removeFooterView(mFooterView);
        mBaseAdapter.setHeaderView(mFailView);
        mStartLading.setVisibility(View.VISIBLE);
        mLoadingProgress.setVisibility(View.INVISIBLE);
    }

    public void onPayWaySuccess(HttpData<ArrayList<PayWayBean>> body) {
        mBaseAdapter.removeHeaderView(mFailView);
        //使用java.util.Iterator
        for (Iterator it = body.getData().iterator(); it.hasNext(); ) {
            PayWayBean obj = (PayWayBean) it.next();
            if (obj.getStatus() == 0) {
                it.remove();
            }
        }
//        if (body.getData().size() <= 4) {
//            if (mBaseAdapter.getFooterLayoutCount() == 0) {
//                mBaseAdapter.addFooterView(mFooterView);
//            }
//        }
        mBaseAdapter.setNewData(body.getData());
    }

    public void onPublishPriceSuccess(String price) {
        mFabiPublishInputUnitPrice.setText(price);
    }
}
